import { ref, watchEffect, computed,onUnmounted } from "vue";

function useUrlParts(url){
  const parts = computed(()=>{
    const _url = url.value
    const i = _url.lastIndexOf('.')
    if(i<0){
      return [_url,'']
    }
    return [_url.substring(0,i),_url.substring(i)]
  })
  return {
    parts
  }
}

function useSortedArray(arr){
  const sorted = computed(()=>{
    const sortedArray = [...arr.value]
    sortedArray.sort((a,b)=>a-b)
    return sortedArray
  })
  return {
    sorted
  }
}

// img元素没有内容的时候,设置了宽度也是0,img元素是行盒,拿不到宽度getBoundingClientRect,getComputedStyle没用
// 创建一个元素放进去就能知道盒子的实际宽度了
// (这里去掉好像也可以)
const cvs = document.createElement("canvas");
cvs.width = 1000;
cvs.height = 1;
const OnePixePng = cvs.toDataURL();

export function useUrl(styleWidth, originUrl, imgSet) {
  const { dpr } = useDPR();
  // 得到文件名和文件类型
  const { parts } = useUrlParts(originUrl);
  // 排序
  const { sorted: sortedSet } = useSortedArray(imgSet);

  const url = computed(() => {
    const _width = styleWidth.value;
    if (_width === 0) {
      return OnePixePng;
    }
    const _dpr = dpr.value;
    const _parts = parts.value;
    const _imgSet = sortedSet.value;
    const width = Math.ceil(_width * _dpr);
    const pre = _parts[0],
      suffix = _parts[1];
    let w = width;
    if (_imgSet.length !== 0) {
      for (let i = 0; i < _imgSet.length; i++) {
        if (width <= _imgSet[i] || i === _imgSet.length - 1) {
          w = _imgSet[i];
          break;
        }
      }
    }
    return `${pre}@${w}${suffix}`;
  });
  return {
    url,
  };
}

export function useWidth(imgRef) {
  const width = ref(0);
  const observer = new ResizeObserver(() => {
    // imgRef.value.width是一个固定值，宽度永远不会变
    width.value = imgRef.value.width;
  });
  let img = null;
  // 使用watchEffect而不是onMounted是因为不知道这个图片是一开始加载出来还是用户操作之后加载出来
  watchEffect(() => {
    const _img = imgRef.value;
    // 如果组件实例_img不见了就用缓存img取消监听
    if (_img) {
      img = _img;
      observer.observe(img);
    } else if (img) {
      observer.unobserve(img);
    }
  });
  return { width };
}

export function useDPR() {
  const dpr = ref(window.devicePixelRatio);
  const observer = new ResizeObserver(() => {
    dpr.value = window.devicePixelRatio;
  });
  observer.observe(document.documentElement);
  onUnmounted(() => {
    observer.unobserve(document.documentElement);
  });
  return {
    dpr,
  };
}
